package du.myseckill.aop;

import du.myseckill.utils.RedissLockUtil;
import org.apache.commons.lang3.ArrayUtils;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import sun.security.util.ArrayUtil;

import static du.myseckill.Const.RedisPrefix.GOODS_LOCK;

@Scope
@Component
@Aspect
//优先级为1，最先执行，并且最后结束
@Order(1)
/**
 * 对秒杀方法加分布式锁
 */
public class RedissonLockAspect {
    @Autowired
    private RedissLockUtil redissLockUtil;


    @Pointcut("execution(* du.myseckill.service.GoodsService.executeSecKillAOPRedisLock(..))")
    public void LockPointCut(){

    }

    @Around("LockPointCut()")
    public Object LockAround(ProceedingJoinPoint joinPoint){
        Object[] args = joinPoint.getArgs();
        MethodSignature methodSignature = (MethodSignature) joinPoint.getSignature();
        String[] parameterNames = methodSignature.getParameterNames();
        int index = ArrayUtils.indexOf(parameterNames, "goodsId");
        long goodsId = (long) args[index];
        redissLockUtil.tryLock(GOODS_LOCK+goodsId,3,20);
        System.out.println("加锁！");
        try {
            Object o = joinPoint.proceed();
            return o;
        } catch (Throwable throwable) {
            throwable.printStackTrace();
            throw new RuntimeException();
        }finally {
            redissLockUtil.unlock(GOODS_LOCK+goodsId);
            System.out.println("解锁！");
        }
    }


}
